text field 的值輸入時,slider也要隨著值得輸入跟著移動位子
@IBAction func TextToSlider(_ sender: Any){
redSlider.setValue(Float(RedValue.text), animated: true)
greenSlider.setValue(Float(GreenValue.text), animated: true)
blueSlider.setValue(Float(blueValue.text), animated: true)
}
以上就大致完成了
接下來有一些小地方需要修改
1.由於調色盤只能輸入數字來更改顏色,所以在text field 我們要給予限制,只能輸入數字(0~9)
所以char 只能在48~57,否則輸入為0
func textField(_ textField : UITextField,shouldChangeCharactersIn range :NSRange,replacementString string : String) ->Bool{
let length = string.lengthOfBytes(using: String.Encoding.utf8)
for loopIndex in 0..<length{
let char = ( string as NSString).character(at: loopIndex)
if char < 48{
textField.text="0"
return false
}
if char > 57{
textField.text="0"
return false
}
}
return true
}
2.還有在設定上要想改變顏色只能輸入(0~255)的值,所以我們要去限制輸入當輸入大於255時,輸入為255,
而小於0或為負數時,輸入為0
@IBAction func TextToSlider(_ sender: Any){
if let RedStringValue = redValue.text{
if let RedIntValue = Int(RedStringValue){
if RedIntValue > 255 {
redValue.text="\(255)"
}
if RedIntValue < 0{
redValue.text="\(0)"
}
redSlider.setValue(Float(RedIntValue), animated: true)
}
}
if let GreenStringValue = greenValue.text{
if let GreenIntValue = Int(GreenStringValue){
if GreenIntValue > 255 {
greenValue.text="\(255)"
}
if GreenIntValue < 0{
greenValue.text="\(0)"
}
greenSlider.setValue(Float(GreenIntValue), animated: true)
}
}
if let BlueStringValue = blueValue.text{
if let BlueIntValue = Int(BlueStringValue){
if BlueIntValue > 255 {
blueValue.text="\(255)"
}
if BlueIntValue < 0{
blueValue.text="\(0)"
}
blueSlider.setValue(Float(BlueIntValue), animated: true)
}
}
}
完成!!!